<template>
  <scroll-view scroll-y="ture" style="height: 100vh">
    <view
      class="panda-container"
      :style="{
        backgroundImage: `url(${oss2('others/panda2023/hx_bg.png')})`,
      }"
    >
      <view
        class="back"
        @click="backIndex"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/but_back2.png')})`,
        }"
      ></view>

      <view
        class="codeInput"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/Input_box.png')})`,
        }"
      >
        <input
          v-model="code"
          placeholder="请输入字符串"
          placeholder-style="color: #777777;"
      /></view>

      <view
        class="cance"
        @click="canceBtn"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/but_cance.png')})`,
        }"
      ></view>

      <view
        class="confirm"
        @click="scanCode"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/but_confirm.png')})`,
        }"
      ></view>
    </view>

    <!-- 弹窗1 -->
    <view class="mode" v-if="showDialog1">
      <view
        class="Dialog_body w-310px h-295px top-209px left-35px"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/tcpic_1.png')})`,
        }"
        ><view
          class="Dialog_back w-119px h-44.5px bottom-47px left-93px"
          @click.stop="openDialog1"
          :style="{
            backgroundImage: `url(${oss2('others/panda2023/button1.png')})`,
          }"
        ></view>
        <view class="Dialog_rule bottom-18.5px"
          >查看<span class="link" @click.stop="openRule1">活动规则</span>
        </view>
      </view>
    </view>

    <!-- 弹窗2 -->
    <view class="mode" v-if="showDialog2">
      <view
        class="Dialog_body w-310px h-295px top-209px left-35px"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/tcpic_3.png')})`,
        }"
        ><view
          class="Dialog_back w-119px h-44.5px bottom-68px left-93px"
          @click.stop="openDialog2"
          :style="{
            backgroundImage: `url(${oss2('others/panda2023/button1.png')})`,
          }"
        ></view>
        <view class="Dialog_rule bottom-36.5px"
          >查看<span class="link" @click.stop="openRule2">活动规则</span>
        </view>
      </view>
    </view>

    <!-- 弹窗3 -->
    <view class="mode" v-if="showDialog3">
      <view
        class="Dialog_body w-310px h-295px top-209px left-35px"
        :style="{
          backgroundImage: `url(${oss2('others/panda2023/tcpic_4.png')})`,
        }"
        ><view
          class="Dialog_back w-119px h-44.5px bottom-68px left-93px"
          @click.stop="openDialog3"
          :style="{
            backgroundImage: `url(${oss2('others/panda2023/button1.png')})`,
          }"
        ></view>
        <view class="Dialog_rule bottom-36.5px"
          >查看<span class="link" @click.stop="openRule3">活动规则</span>
        </view>
      </view>
    </view>

    <oreo-action-sheet
      :show="kefuShow"
      @cancel="kefuShow = false"
      cancel-text="取消"
    >
      <button class="phoneStyle" @click="PhoneCall">400-0880-325</button>
      <button open-type="contact" class="kefu_btn">在线客服</button>
    </oreo-action-sheet>

    <!-- 活动规则弹窗 -->
    <rule-popup
      v-if="showRule"
      @closekf="kefuShow = false"
      @openkf="kefuShow = true"
      @close="showRule = false"
    />
  </scroll-view>


</template>

<script setup>
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onShareAppMessage,
} from "@dcloudio/uni-app";
import { ref } from "vue";
import { oss2, generateSign2, message } from "@/utils/utils";
import RulePopup from "./components/rule-popup.vue";
import { userLogin } from "@/services/utils";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";

const code = ref("");

const showDialog1 = ref(false);
const showDialog2 = ref(false);
const showDialog3 = ref(false);
const showRule = ref(false);
const kefuShow = ref(false);

onLoad(async (query) => {});

onShow(() => {
  // 用户进入时间
  enterTime = new Date();
  getApp().accessLogAdd();
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime?.getTime() - enterTime?.getTime()) / 1000;
});

const linkTo = (url) => uni.navigateTo({ url });

const scanCode = () => {
  getApp().emdlz2(
    "track",
    "event",
    "pandas_campaign_hm_input_page",
    "click",
    "confirm",
    ""
  );

  if (code.value === "") return message("请输入字符串!");
  const body = {
    userValue: uni.getStorageSync("OPENID"),
    qrCode: code.value,
    source: "oreo",
    timestamp: Date.parse(new Date()),
  };
  uni.request({
    url: `${process.env.PANDA_URL2}/zex-qr/api/qr/validation`,
    method: "get",
    data: {
      ...body,
      ...{ sign: generateSign2(body) },
    },

    success: async (requestRes) => {
      console.log(requestRes);
      if (requestRes.data.code === 200) {
        // 是否登录注册
        if (!uni.getStorageSync("TOKEN")) {
          // 静默拿取微信用户的 openId 与 unionId 信息
          uni.login({
            provider: "weixin",
            success: async (res) => {
              console.log(res);
              const loginParam = {
                type: 1,
              };
              loginParam.code = res.code;
              const { data } = await userLogin(loginParam);
              uni.setStorageSync("TOKEN", data?.accessToken);
              uni.setStorageSync("OPENID", data?.openId);
              uni.setStorageSync("UNIONID", data?.unionId);
              getApp().emdlz("set", "user", "openid", data?.openId);
              getApp().emdlz("set", "user", "unionId", data?.unionId);

              linkTo(
                `/campaign/pages/panda2023/webview?accesstoken=${uni.getStorageSync(
                  "TOKEN"
                )}&code=${code.value}&openid=${uni.getStorageSync(
                  "OPENID"
                )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
                  getApp().globalData.user.memberScore.memberId
                }&agree=${uni.getStorageSync("PANDAAGREE")}`
              );
              code.value = "";
            },
          });
        } else {
          linkTo(
            `/campaign/pages/panda2023/webview?accesstoken=${uni.getStorageSync(
              "TOKEN"
            )}&code=${code.value}&openid=${uni.getStorageSync(
              "OPENID"
            )}&unionid=${uni.getStorageSync("UNIONID")}&memberid=${
              getApp().globalData.user.memberScore.memberId
            }&agree=${uni.getStorageSync("PANDAAGREE")}`
          );
          code.value = "";
        }
      } else if ([4000].includes(requestRes.data.code)) {
        code.value = "";
        showDialog1.value = true;
      } else if ([4001].includes(requestRes.data.code)) {
        code.value = "";
        showDialog2.value = true;
      } else if ([4002].includes(requestRes.data.code)) {
        code.value = "";
        showDialog3.value = true;
      } else {
        code.value = "";
        uni.showToast({
          title: requestRes.data.message,
          icon: "none",
          duration: 2000,
        });
      }
    },
    fail(requestErr) {
      code.value = "";
      uni.showToast({
        title: requestErr.data.message,
        icon: "none",
        duration: 2000,
      });
    },
  });
};

const linkToWebView = (url) => {
  linkTo(
    `/pages/webView/webview?token=${uni.getStorageSync(
      "TOKEN"
    )}&openid=${uni.getStorageSync("OPENID")}&unionid=${uni.getStorageSync(
      "UNIONID"
    )}&memberid=${
      getApp().globalData.user.memberScore.memberId
    }&webSrc=${url}&agree=${uni.getStorageSync(
      "PANDAAGREE"
    )}&shareTitel=泡出童心 玩在一起&shareImg=${oss2(
      "others/panda2023/sharepic2.png"
    )}&path=${"/campaign/pages/panda2023/index?from=pubid:shareback;aid:sharecard"}`
  );
};

const openDialog1 = () => {
  showDialog1.value = false;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_hm_input_page",
    "click",
    "pop-up_return_4000",
    ""
  );
};
const openDialog2 = () => {
  showDialog2.value = false;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_hm_input_page",
    "click",
    "pop-up_check_activity_rule_4001",
    ""
  );
};
const openDialog3 = () => {
  showDialog3.value = false;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_hm_input_page",
    "click",
    "pop-up_return_4002",
    ""
  );
};

const openRule1 = () => {
  showRule.value = true;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_hm_input_page",
    "click",
    "pop-up_check_activity_rule_4000",
    ""
  );
};
const openRule2 = () => {
  showRule.value = true;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_hm_input_page",
    "click",
    "pop-up_check_activity_rule_4001",
    ""
  );
};
const openRule3 = () => {
  showRule.value = true;
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_hm_input_page",
    "click",
    "pop-up_check_activity_rule_4002",
    ""
  );
};

const PhoneCall = () => {
  uni.makePhoneCall({
    phoneNumber: "400-0880-325",
  });
};

const backIndex = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_hm_input_page",
    "click",
    "return",
    ""
  );
  uni.navigateBack({
    delta: 1,
  });
};

const canceBtn = () => {
  getApp().emdlz(
    "track",
    "event",
    "pandas_campaign_hm_input_page",
    "click",
    "cancel",
    ""
  );

  uni.navigateBack({
    delta: 1,
  });
};

onShareAppMessage((e) => {
  // const pages = getCurrentPages();
  // const currentPage = pages[pages.length - 1];
  // console.log(pages);
  // const pageUrl = currentPage.$page.fullPath;

  const shareObj = {
    title: "泡出童心 玩在一起", // 默认是小程序的名称(可以写slogan等)
    path: "/campaign/pages/panda2023/index?from=pubid:shareback;aid:sharecard", // 默认是当前页面，必须是以‘/’开头的完整路径
    imageUrl: oss2("others/panda2023/sharepic2.png"), //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
    success: (res) => {
      // 转发成功之后的回调
      if (res.errMsg == "shareAppMessage:ok") {
      }
    },
    fail: (err) => {
      // 转发失败之后的回调
      console.log("转发失败之后的回调", err);
      if (res.errMsg == "shareAppMessage:fail cancel") {
        // 用户取消转发
        console.log("用户取消转发");
      } else if (res.errMsg == "shareAppMessage:fail") {
        // 转发失败，其中 detail message 为详细失败信息
        console.log("转发失败，其中detail message 为详细失败信息");
      }
    },
    complete: () => {
      // 转发结束之后的回调（转发成不成功都会执行）
      console.log("转发结束之后的回调（转发成不成功都会执行）");
    },
  };
  console.log(shareObj);
  return shareObj;
});
</script>

<style>
page {
  background-color: #0a2080 !important;
}
</style>
<style lang="less" scoped>
.panda-container {
  width: 100%;
  background-color: #1335b3;
  height: 724px;
  background-repeat: no-repeat;
  background-position: top left;
  background-size: 375px 100%;
  position: relative;

  .back {
    position: absolute;
    top: 21px;
    left: 0;
    width: 61px;
    height: 32px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 61px 100%;
  }
  .codeInput {
    position: absolute;
    top: 462px;
    left: 30.5px;
    width: 315px;
    height: 65.5px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 315px 100%;
    input {
      width: 230px;
      height: 20px;
      line-height: 20px;
      font-size: 18px;
      padding-left: 26px;
      padding-top: 20px;
    }
  }

  .cance {
    position: absolute;
    top: 546.5px;
    left: 36.5px;
    width: 142.5px;
    height: 53px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 142.5px 100%;
  }
  .confirm {
    position: absolute;
    top: 546.5px;
    right: 35px;
    width: 142.5px;
    height: 53px;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 142.5px 100%;
  }
}

.mode {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 90;
  background-color: rgba(10, 28, 108, 0.8);
  .Dialog_body {
    position: absolute;
    background-repeat: no-repeat;
    background-position: top left;
    background-size: 100% 100%;
    .Dialog_back {
      position: absolute;
      background-repeat: no-repeat;
      background-position: top left;
      background-size: 100% 100%;
    }
    .Dialog_rule {
      width: 100%;
      text-align: center;
      font-size: 12.5px;
      position: absolute;
      color: #0f2989;
      .link {
        color: #30a8fb;
        text-decoration: underline;
        margin-left: 5px;
      }
    }
  }
}

.phoneStyle {
  font-size: 16px;
  color: #007aff;
}
.kefu_btn {
  font-size: 16px;
  margin: 0 !important;
  border-radius: 0 !important;
  background: none !important;
}
</style>
